package com.fy.service.impl;

import com.fy.dao.EpcDictDao;
import com.fy.dao.EpcUserDao;
import com.fy.dao.EpcUserRecordDao;
import com.fy.entity.EpcDict;
import com.fy.entity.EpcUser;
import com.fy.entity.EpcUserRecord;
import com.fy.entity.PageEntity;
import com.fy.service.EpcUserService;
import com.fy.utils.ObjectUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.map.HashedMap;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;


@Service("epcUserService")
public class EpcUserServiceImpl implements EpcUserService {
    @Autowired
    private EpcUserDao epcUserDao;
    @Autowired
    private EpcUserRecordDao epcUserRecordDao;
    @Autowired
    private EpcDictDao epcDictDao;

    //dao
    String mapperName = EpcUserDao.class.getName();


    /***
     * <b>查询的分页</b>
     * @param record
     * @return
     */
    public List<EpcUser> getEpcUserListPage(EpcUser record, PageEntity page) {
        EpcDict dict1 = new EpcDict();
        dict1.setDictKey("time_effective_setting");
        EpcDict dict = epcDictDao.getEpcDictByKey(dict1);
        record.setDay(dict.getDictValue());

        PageHelper.startPage(page.getCurrentPage(), page.getPageSize());
        List<EpcUser> epcUserList = epcUserDao.getEpcUserListPage(record);
        PageInfo<EpcUser> pageInfo = new PageInfo<>(epcUserList);

        page.setTotalResultSize((int)pageInfo.getTotal());

        //		return Result.ok(pageInfo.getTotal(), pageInfo.getList());
        return pageInfo.getList();
    }



    /***
     * <b>添加</b>
     * @param record
     * @return
     */
    public Long editEpcUser(EpcUser record) throws Exception {
        /**
         *  todo 更新人员信息  HkPerson，以海康信息为准
         */
//        HkPerson personInfo = null;
//        try {
//            personInfo = PersonInterface.getPersonInfo(record.getIdCard(), record.getPhone());
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        if(personInfo != null){
//            record.setPhone(personInfo.getPhone()==null? record.getPhone():personInfo.getPhone());
//            record.setJobNo(personInfo.getJobNo());
//            record.setPersonId(personInfo.getPersonId());
//            record.setGender(personInfo.getGender());
//            record.setUserName(personInfo.getPersonName());
//        }

        if(ObjectUtils.isNotNull(record.getId())){
            return this.epcUserDao.updateEpcUserById(record);
        }else{
            EpcUser oldUser = this.epcUserDao.getEpcUserByIdCard(record);
            if(ObjectUtils.isNotNull(oldUser)){
                record.setId(oldUser.getId());
               this.epcUserDao.updateEpcUserById(record);
            }else{
               this.epcUserDao.addEpcUser(record);
            }

            EpcUserRecord urecord = new EpcUserRecord();
            urecord.setEpcUserId(record.getId());
            return epcUserRecordDao.addEpcUserRecord(urecord);
        }

    }

    /**
     * 根据id查询
     * @param record
     * @return
     */
    public EpcUser getEpcUserById(EpcUser record){
        EpcDict dict1 = new EpcDict();
        dict1.setDictKey("time_effective_setting");
        EpcDict dict = epcDictDao.getEpcDictByKey(dict1);

        record.setDay(dict.getDictValue());
        return  this.epcUserDao.getEpcUserById(record);
    }

    /**
    *批量删除
     */
    public void deleteEpcUserBatch(String ids) {
        Map<String,Object> dataMap = new HashedMap();
        dataMap.put("ids",ids);
        epcUserDao.deleteEpcUserBatch(dataMap);
    }

    public Map<String, Object> userStatusSatistics() {
        Map<String, Object> resMap = new HashMap<>();

        EpcDict dict1 = new EpcDict();
        dict1.setDictKey("time_effective_setting");
        EpcDict dict = epcDictDao.getEpcDictByKey(dict1);


        Integer eCount = this.epcUserDao.getEpcUserCountByStatus(1,dict.getDictValue());
        resMap.put("effectiveCount", eCount);
        Integer noECount = this.epcUserDao.getEpcUserCountByStatus(2,dict.getDictValue());
        resMap.put("notEffectiveCount", noECount);
        return resMap;
    }

    public List<Map<String, Object>> userRecordSatistics(String startDate, String endDate) {
        List<Map<String, Object>> resList = new ArrayList<>();
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        endDate = simpleDateFormat.format(date);
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DATE, -7);
        startDate = simpleDateFormat.format(c.getTime());
        List<Map<String, Object>> countList  = epcUserRecordDao.getUserRecordSatistics(startDate, endDate);
        for (int i = 0; i < 7; i++) {
            c.setTime(c.getTime());
            c.add(Calendar.DATE, 1);
            String dateStr = simpleDateFormat.format(c.getTime());
            Map<String,Object> dateMap = new HashMap<>();
            dateMap.put("date",dateStr);
            dateMap.put("count",0);
            for (int j = 0; j < countList.size(); j++) {
                if(dateStr.equals(countList.get(j).get("date").toString())){
                    dateMap.put("count",countList.get(j).get("num"));
                }
            }
            resList.add(dateMap);
        }
        return  resList;
    }

    public HSSFWorkbook userExport(List<EpcUser> userList) {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("防疫人员");

        HSSFFont font1 = workbook.createFont();
        font1.setFontHeightInPoints((short) 12);
        HSSFCellStyle style =  createStyle(workbook);
        style.setWrapText(true);
        style.setFont(font1);

        //创建表头
        HSSFRow rowTitle = sheet.createRow(0);
        rowTitle.createCell(0).setCellValue("姓名");
        rowTitle.createCell(1).setCellValue("部门");
        rowTitle.createCell(2).setCellValue("班组");
        rowTitle.createCell(3).setCellValue("身份证号");
        rowTitle.createCell(4).setCellValue("手机号");
        rowTitle.createCell(5).setCellValue("家庭住址");
        rowTitle.createCell(6).setCellValue("体温");
        rowTitle.createCell(7).setCellValue("状态");
        rowTitle.createCell(8).setCellValue("提交日期");
        for (int j = 0; j <=8 ; j++) {
            rowTitle.getCell(j).setCellStyle(style);
            sheet.setColumnWidth(j, 6000);
        }
        sheet.setColumnWidth(3, 7000);
        sheet.setColumnWidth(5, 8000);
        for (int i = 0; i < userList.size(); i++) {
            HSSFRow row = sheet.createRow(i+1);
            row.createCell(0).setCellValue(userList.get(i).getUserName()==null?"":userList.get(i).getUserName());
            row.createCell(1).setCellValue(userList.get(i).getDeptName()==null?"":userList.get(i).getDeptName());
            row.createCell(2).setCellValue(userList.get(i).getGroupName()==null?"":userList.get(i).getGroupName());
            row.createCell(3).setCellValue(userList.get(i).getIdCard()==null?"":userList.get(i).getIdCard());
            row.createCell(4).setCellValue(userList.get(i).getPhone()==null?"":userList.get(i).getPhone());
            row.createCell(5).setCellValue(userList.get(i).getAddress()==null?"":userList.get(i).getAddress());
            row.createCell(6).setCellValue(userList.get(i).getTemperature()==null?"":userList.get(i).getTemperature());
            int status = userList.get(i).getStatus();
            if(status == 1){
                row.createCell(7).setCellValue("正常");
            }else{
                row.createCell(7).setCellValue("异常");
            }
            row.createCell(8).setCellValue(userList.get(i).getSubmitDate()==null?"":userList.get(i).getSubmitDate());

            for (int j = 0; j <=8 ; j++) {
                row.getCell(j).setCellStyle(style);
            }
        }
        return workbook;
    }

    private HSSFCellStyle createStyle(HSSFWorkbook workbook){
        HSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER); // 居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直
        //设置上下左右四个边框宽度
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        //设置上下左右四个边框颜色
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        return  style;
    }

    private HSSFCellStyle createStyleLeft(HSSFWorkbook workbook){
        HSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER); // 居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直
        //设置上下左右四个边框宽度
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        //设置上下左右四个边框颜色
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        return  style;
    }

    public void editEpcUserTempByCard(EpcUser epcUser) {
        this.epcUserDao.editEpcUserTempByCard(epcUser);
    }
}
